﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Caching;
using ShrinkWrap.Minifier;
using ShrinkWrap.Exceptions;

namespace ShrinkWrap.HttpHandler
{
    public class CachingAggregator : Aggregator
    {
        Cache cache;

        public CachingAggregator(IMinifier minifier, CompositeUri composite, Func<String, String> mapPath, int maxConstituents, Cache cache)
            : base(minifier, composite, mapPath, maxConstituents)
        {
            this.cache = cache;
        }

        /// <summary>
        /// An aggregated, minified representation of the URI, fetched from the application cache.
        /// On cache miss, aggregate will first be read into cache.
        /// </summary>
        public override String GetAggregate()
        {
            if (cache[CompositeUri.ToString()] == null)
            {
                // Add dependency on contituent files so that we re-calculate aggregate if any change
                IEnumerable<String> filenames = CompositeUri.ConstituentUris.Select(uri => mapPath(uri.LocalPath));
                CacheDependency filesModified = new CacheDependency(filenames.ToArray());

                cache.Insert(CompositeUri.ToString(), base.GetAggregate(), filesModified);
            }
            return cache[CompositeUri.ToString()] as String;
        }
    }
}
